package com.feinno.module.security.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.feinno.framework.common.exception.BusinessException;
import com.feinno.framework.common.service.EntityServiceImpl;
import com.feinno.framework.utils.Encodes;
import com.feinno.module.security.dao.UserDao;
import com.feinno.module.security.domain.User;
import com.feinno.module.security.service.UserService;
import com.feinno.module.security.utils.Digests;

@Service("userService")
public class UserServiceImpl extends EntityServiceImpl<User, UserDao> implements
		UserService {

	@Override
	public User findUserByLoginid(String loginid) {
		return getEntityDao().findByLoginid(loginid);
	}

	@Override
	public void createUser(User user) throws BusinessException {
		try {
			User exsit = findUserByLoginid(user.getLoginid());
			if (exsit != null) {
				throw new RuntimeException("用户登录名:[" + user.getLoginid()
						+ "]已经存在");
			}
			if (StringUtils.isNotBlank(user.getPasswd())) {
				entryptPassword(user);
			}
			super.save(user);
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
	}

	@Override
	public void updateUser(User user) throws BusinessException {
		try {
			User orginalUser = get(user.getId());
			String oPswd = orginalUser.getPasswd();
			String oSalt = orginalUser.getSalt();
			String oLoginid = orginalUser.getLoginid();
			orginalUser = null;
			user.setPasswd(oPswd);
			user.setSalt(oSalt);
			user.setLoginid(oLoginid);
			update(user);
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}

	}

	@Override
	public void changePassword(User user, String newPassword)
			throws BusinessException {
		if (StringUtils.isNotBlank(newPassword)) {
			user.setPasswd(newPassword);
			entryptPassword(user);
			update(user);
		}
	}

	@Override
	public boolean validatePassword(User user, String plaintPassword)
			throws BusinessException {
		return entryptPassword(plaintPassword, user.getSalt()).equals(
				user.getPasswd());
	}

	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 * 
	 * @param user
	 */
	private void entryptPassword(User user) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		user.setSalt(Encodes.encodeHex(salt));
		user.setPasswd(entryptPassword(user.getPasswd(),
				Encodes.encodeHex(salt)));
	}

	private String entryptPassword(String plainPassword, String salt) {
		return Encodes.encodeHex(Digests.sha1(plainPassword.getBytes(),
				Encodes.decodeHex(salt), HASH_INTERATIONS));
	}

}
